package com.bytecub.simulate.device.task;

import com.bytecub.common.constants.BCConstants;
import com.bytecub.simulate.device.common.LogContext;
import com.bytecub.simulate.device.common.constants.SimulateConstants;
import com.bytecub.simulate.device.instance.DeviceInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 *  * ByteCub.cn.
 *  * Copyright (c) 2020-2021 All Rights Reserved.
 *  * 
 *  * @author bytecub@163.com  songbin
 *  * @version Id: DeviceReporterTask.java, v 0.1 2021-02-24  Exp $$
 *  
 */
public class DeviceReporterTask implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(DeviceReporterTask.class);
    private long logindex;
    public static ThreadLocal<Long> threadLocal = new ThreadLocal<>();

    private DeviceInstance deviceInstance;
    private String taskName;

    public DeviceReporterTask(String taskName, DeviceInstance deviceInstance) {
        this.deviceInstance = deviceInstance;
        this.taskName = taskName;
    }

    @Override
    public void run() {
        LogContext.CONTEXT.set(DeviceInstance.snowflake.nextId());
        while (true) {
            try {
                long startTime = System.currentTimeMillis();
                log.info("logId:{},threadId:{},deviceId:{}, start time:{}，delay time:{}", LogContext.CONTEXT.get(), Thread.currentThread().getId(), deviceInstance.getDeviceCode(), startTime / 1000, SimulateConstants.DELAY_TIME);
                deviceInstance.reportData();
                Thread.sleep(SimulateConstants.DELAY_TIME);
                long consumeTime = System.currentTimeMillis() - startTime;
                log.info("logId:{},threadId:{},deviceId:{}, consume time:{}s", LogContext.CONTEXT.get(), Thread.currentThread().getId(), deviceInstance.getDeviceCode(), consumeTime / 1000);
            } catch (Exception e) {
                log.info("logId:{},threadId:{},deviceId:{}, 异常", LogContext.CONTEXT.get(), Thread.currentThread().getId(), deviceInstance.getDeviceCode(), e);
            }
        }

    }
}
